# _*_ encoding:utf-8 _*_

import django_filters
from django.db.models import Q


def get_filter(model_class, field1, field2=None):
    """
    获取特定过滤器
    :param model_class: 模型类
    :param field1: 过滤字段
    :param field2: 过滤字段
    :return: 过滤器
    """

    class Filter(django_filters.FilterSet):
        """自定义过滤器"""

        keyword = django_filters.CharFilter(method='handelField')

        def handelField(self, queryset, name, value):
            f1 = {'__'.join([field1, 'contains']): value}
            f2 = {'__'.join([field2, 'contains']): value} if field2 else {}

            return queryset.filter(Q(**f1) | Q(**f2 or f1))

        class Meta:
            model = model_class
            fields = []

            # fields = {
            #     'name': ['exact', 'contains', 'startswith', 'endswith'],
            #     'price': ['gt', 'lt', 'gte', 'lte']
            # }

    return Filter
